package com.tubang.component.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.ResultData;
import com.tubang.common.util.StringUtils;
import com.tubang.component.component.UploadUtils;
import com.tubang.component.util.RequestUtil;

@RestController
public class UploadMonofile {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private UploadUtils uploadUtils;

	@PostMapping("tubang/uploadMonofile")
	public ResultData uploadMonofile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		Map<String, String> map = new HashMap<>();
		try {
			String url = uploadUtils.uploadPic(file, request);
			logger.info("method[uploadMonofile] : 上传文件成功url为： {}", url);
			if (StringUtils.isBlank(url)) {
				return ResultData.result(false).setMsg("图片的url为空，请先上传图片");
			}
			String Filename = file.getOriginalFilename();
			map.put("fileName", Filename);
			map.put("url", url);
			return ResultData.result(true).setData(map);
		} catch (Exception e) {
			logger.error("method[uploadMonofile] : 上传文件失败，失败原因为： {}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false);
		}
	}
	
	@PostMapping("tubang/uploadPicByBase64")
	public ResultData uploadPicByBase64(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	String imgBase64Str = GsonQuick.getString(receivePostJson, "imgBase64Str");
		logger.info("method[uploadPicByBase64] : 请求的base64字符串为 {}", imgBase64Str);
		try {
			Map<String, String> map = new HashMap<>();
			String url = uploadUtils.uploadPicByBase64(imgBase64Str, request);
			logger.info("method[uploadMonofile] : 上传文件成功url为： {}", url);
			if (StringUtils.isBlank(url)) {
				return ResultData.result(false).setMsg("图片的url为空，请先上传图片");
			}
			map.put("url", url);
			return ResultData.result(true).setData(map);
		} catch (Exception e) {
			logger.error("method[uploadMonofile] : 上传文件失败，失败原因为： {}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false);
		}
	}

}
